//
//  LogInVC.m
//  TMSDriver
//
//  Created by mac on 2019/5/14.
//  Copyright © 2019年 zhuchongjin. All rights reserved.
//

#import "LogInVC.h"
#import "HomeXieYView.h"
#import <SafariServices/SafariServices.h>
#import "RegisterVC.h"
#import "ForgetPWVC.h"
#import "CJWKWebViewVC.h"
#import "HomeVC.h"
/**  极光  **/
#import "JPUSHService.h"
#import "CJDateTime.h"
#import "ImgVAouthCode.h"
#import "CJAppInfo.h"
#import "StrongReminderView.h"
#import "NewForgetPWVC.h"

@interface LogInVC ()<SFSafariViewControllerDelegate>{
    int time;
}
@property (strong, nonatomic) CJTextField *fieldAccount;
@property (strong, nonatomic) CJTextField *fieldPW;
@property (strong, nonatomic) CJTextField *fieldBranchCode;
@property (nonatomic,copy) NSString *strBranchCode;
@property (nonatomic,copy) NSString *strSecureTextEntry; // 1 安全模式
@property (nonatomic,strong) CJImageView * imgSecureEntry;
// 验证码相关操作
@property (nonatomic,strong) FlexTouchView *toucViewGetAouthCode; //
@property (nonatomic,strong) UIView *viewAouthCodeBG; // 验证码superView
@property (nonatomic,strong) CJLabel *labCodeTime;
@property (nonatomic,strong) UIView *viewLineCode; // 底部分割线
@property (nonatomic,strong) CJTextField *fieldAouthCode; // 验证码
@property (nonatomic,strong) FlexTouchView *touchBranch;
@property (nonatomic,strong) UIView *viewBranchLine;
@property (nonatomic,strong) CJImageView *imgVSelect;
@property (nonatomic,assign) BOOL isAgree;
@property (nonatomic,strong) UILabel *labPrivacyTitle;
@property (nonatomic, strong) HomeXieYView *xieyiView;
@end

@implementation LogInVC
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    
    @weakify(self);
    [CJNetWork getBrachcCodeSuccess:^(id  _Nullable responseObject) {
        @strongify(self);
        if ([CJControl getIsLoginNeedSMS]) {
            self.toucViewGetAouthCode.hidden = NO;
            self.viewAouthCodeBG.hidden = NO;
            self.viewLineCode.hidden = NO;
        }else{
            self.toucViewGetAouthCode.hidden = YES;
            self.viewAouthCodeBG.hidden = YES;
            self.viewLineCode.hidden = YES;
        }
        
        if ([CJControl getHideBranche]) {
            self.touchBranch.hidden = YES;
            self.viewBranchLine.hidden = YES;
        }else{
            self.touchBranch.hidden = NO;
            self.viewBranchLine.hidden = NO;
        }
    }];
    
    [CJNetWork getBrachcCodeListSuccess:^(id  _Nullable responseObject) {
        @strongify(self);
        NSArray *list = (NSArray *)responseObject;
        if (list.count > 0) {
            NSDictionary *dic = list[0];
            self.fieldBranchCode.text = [CJControl getThreeUnaryValueStr:dic[@"groupName"]];
            self.strBranchCode = [CJControl getThreeUnaryValueStr:dic[@"code"]];
            [[NSUserDefaults standardUserDefaults] setObject:self.strBranchCode forKey:@"partyGroupCode"];
        }
    }];
    
    if (![CJControl getIsFirstLogInSucess]) {
        self.isAgree = YES;
        self.imgVSelect.image = [UIImage imageNamed:@"selected"];
    }
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self setTitleName:@"登录"];
    self.view.backgroundColor = [UIColor cjWhiteColor];
    self.strSecureTextEntry = @"1";
    self.isAgree = NO;
    [self createView];
    
#ifdef DEBUG
    //        self.fieldAccount.text =   @"17700000006";  //@"17750000004"; @"17756100004";//
    //        self.fieldPW.text = @"abcd1234";
#else
    // Release 模式的代码...
#endif
    
    self.strBranchCode = @"";
    self.fieldBranchCode.textColor = [UIColor cjMainTextColor];
    self.fieldBranchCode.enabled = NO;
    
}

- (void)createView{
    
    CGRect rcFrame = CGRectMake(0, kTopHeight + 50, [[UIScreen mainScreen] bounds].size.width, 0);
    FlexFrameView *header = [[FlexFrameView alloc] initWithFlex:@"LogInView" Frame:rcFrame Owner:self];
    header.flexibleHeight = YES;
    self.labPrivacyTitle.text = CJStringWithFormat(@"《%@隐私政策》",[CJAppInfo appName]);
    [header layoutIfNeeded];
    [self.view addSubview:header];
}

- (void)btnActionSecureTextEntry{
    
    if ([self.strSecureTextEntry isEqualToString:@"1"]) {
        self.strSecureTextEntry = @"0";
        self.imgSecureEntry.image = [UIImage imageNamed:@"icon_open_eye"];
        self.fieldPW.secureTextEntry = NO;
        //        self.filedSurePW.secureTextEntry = NO;
        
    }else{
        self.strSecureTextEntry = @"1";
        self.imgSecureEntry.image = [UIImage imageNamed:@"icon_close_eye"];
        self.fieldPW.secureTextEntry = YES;
        //        self.filedSurePW.secureTextEntry = YES;
    }
}

#pragma mark ----------选择机构 ----
-(void)touchViewGetBranchCodeListAction{
    
    [self.view endEditing:NO];
    
    @weakify(self);
    [CJNetWork getBrachcCodeListSuccess:^(id  _Nullable responseObject) {
        
        @strongify(self);
        NSArray *list = (NSArray *)responseObject;
        NSMutableArray *arrMutar = [[NSMutableArray alloc]init];
        NSMutableArray *arrMutarCodes = [[NSMutableArray alloc]init];
        
        if (list.count > 0) {
            
            [list enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                [arrMutar addObject:obj[@"groupName"]];
                [arrMutarCodes addObject:obj[@"code"]];
            }];
        }
        [self btnSelectList:arrMutar listCodes:arrMutarCodes title:@""];
        
    }];
}


- (void)btnSelectList:(NSArray *)list listCodes:(NSMutableArray *)arryCodes title:(NSString *)strTitle{
    
    [self.view endEditing:NO];
    BRStringPickerView *stringPickerView = [[BRStringPickerView alloc]initWithPickerMode:BRStringPickerComponentSingle];
    stringPickerView.title = strTitle;
    stringPickerView.dataSourceArr = list;
    @weakify(self);
    stringPickerView.resultModelBlock = ^(BRResultModel *resultModel) {
        @strongify(self);
        self.fieldBranchCode.text = resultModel.selectValue;
        self.strBranchCode = arryCodes[resultModel.index];
    };
    
    BRPickerStyle *customStyle = [BRPickerStyle pickerStyleWithThemeColor:[UIColor cjMainColor]];
    stringPickerView.pickerStyle = customStyle;
    [stringPickerView show];
}

//是否选中
- (void)selecImgvAction{
    if (self.isAgree) {
        self.isAgree = NO;
        self.imgVSelect.image = [UIImage imageNamed:@"zcj_unSelected"];
    } else {
        self.isAgree = YES;
        self.imgVSelect.image = [UIImage imageNamed:@"selected"];
    }
}


- (void)btnPrivacyAgreement{
    
    //    0716 release0716-agreement-newhtml 修改协议地址传参agreementType：协议类型:1=司机端隐私协议/2=司机端用户协议/3=司机端注销协议/4=司机端物流协议/5=接单协议/6=司机端SDK协议/7=货主端隐私协议/8=货主端用户协议/9=货主端注销协议/10=货主端物流协议/11=货主端SDK协议/12=PC端隐私协议/13=PC端用户协议/14=PC端物流协议/15=网商协议  例如 /agreement/agreement.html?agreementType=1
    
    CJWKWebViewVC *vc = [CJWKWebViewVC new];
    vc.strTitle = @"隐私协议";
    vc.useUTF8 = YES;
    vc.strUrl = CJStringWithFormat(@"%@/agreement/agreement.html?agreementType=7",CJBaseUrl);
    [self pushVc:vc];
}

/// 忘记密码
- (void)touchViewForgetPassWordAction{
//    ForgetPWVC *vc = [[ForgetPWVC alloc]init];
//    [self pushVc:vc];
    NewForgetPWVC *vc = [[NewForgetPWVC alloc]init];
    [self pushVc:vc];
}

/// 注册账户
- (void)touchViewRegisterAccountAction{
    RegisterVC *vc = [RegisterVC new];
    [self pushVc:vc];
}

#pragma mark ----------验证码相关操作
- (void)touchViewPhoneVerCodeAction{
    [self.view endEditing:NO];
    if ([self.strBranchCode isEqualToString:@""]){
        [CJAlert showStringDismissWithDelay:@"请选择机构"];
        return;
    }
    
    if (![CJRegular getcheckPhone:self.fieldAccount.text]) {
        [[[AFViewShaker alloc] initWithView:self.fieldAccount] shakeWithDuration:[ShakerTime floatValue] completion:^{
            [CJAlert showStringDismissWithDelay:@"请填写正确的手机号"];
        }];
    }else{
        
        NSString *strURL = CJStringWithFormat(@"%@/ntocc-basic-api/party/validPhoneNoError",CJBaseUrl);
        NSDictionary *dicPar = @{@"phone":CJStringWithFormat(@"%@",self.fieldAccount.text),
                                 @"branchCode":[CJControl getThreeUnaryValueStr:self.strBranchCode],
        };
        @weakify(self);
        [[HDNetworking sharedHDNetworking] GET:strURL parameters:dicPar success:^(id  _Nonnull responseObject) {
            
            //            {
            //                "msg": "手机号没有注册",
            //                "data": "no",
            //                "status": 0
            //            }
            
            NSString *strData = (NSString *)responseObject;
            
            if ([strData isEqualToString:@"no"]) {
                //                [ws getSendVerificationCode];
                [CJAlert showStringDismissWithDelay:@"手机号没有注册"];
                
            }else{
                
                [[ImgVAouthCode shared] initWithPhoneNum:self.fieldAccount.text ClickOnSure:^(NSString * _Nonnull strSure) {
                    @strongify(self);
                    [self getSendVerificationCodeWithImageCode:strSure];
                } ClickOnCancle:^(NSString * _Nonnull strCancle) {
                    
                }];
            }
            
        } failure:^(NSError * _Nonnull error) {
            DLog(@"++++++++%@",error);
            
        }];
    }
}

- (void)getSendVerificationCodeWithImageCode:(NSString *)imgVCode{
    
    if ([self.strBranchCode isEqualToString:@""]){
        [CJAlert showStringDismissWithDelay:@"请选择机构"];
        return;
    }
    if (![CJRegular getcheckPhone:self.fieldAccount.text]) {
        [CJAlert showStringDismissWithDelay:@"请填写正确的手机号"];
        return;
    }
    
    NSString *strURL = CJStringWithFormat(@"%@/ntocc-tps-api/sms/sendVerificationCode",CJBaseUrl);
    NSDictionary *dicPar = @{@"phone":CJStringWithFormat(@"%@",self.fieldAccount.text),
                             @"partyGroupCode":[CJControl getThreeUnaryValueStr:self.strBranchCode],
                             @"imageCode":imgVCode
    };
    
    @weakify(self);
    [[HDNetworking sharedHDNetworking] POST:strURL parameters:dicPar success:^(id  _Nonnull responseObject) {
        
        @strongify(self);
        self.toucViewGetAouthCode.userInteractionEnabled = NO;
        time = 60;
        [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timerFireM:) userInfo:nil repeats:YES];
        
    } failure:^(NSError * _Nonnull error) {
        DLog(@"++++++++%@",error);
        
    }];
}

- (void)timerFireM:(NSTimer *)theTimer{
    
    NSString * str =[NSString stringWithFormat:@"(%ds)",time];
    self.labCodeTime.text = str;
    time--;
    if (time==0) {
        [theTimer invalidate];
        time=60;
        self.labCodeTime.text = @"验证码";
        self.toucViewGetAouthCode.userInteractionEnabled = YES;
    }
}

- (void)touchViewLogInAction{
    [self.view endEditing:NO];
    if (![CJRegular getcheckPhone:self.fieldAccount.text]) {
        [[[AFViewShaker alloc] initWithView:self.fieldAccount] shakeWithDuration:[ShakerTime floatValue] completion:^{
            [CJAlert showStringDismissWithDelay:CJPhoneNumError];
        }];
    }
    else if ([self.strBranchCode isEqualToString:@""]){
        [CJAlert showStringDismissWithDelay:@"请选择机构"];
    }else if (self.isAgree == NO){
        [CJAlert showStringDismissWithDelay:CJStringWithFormat(@"请阅读并同意《%@隐私政策》",[CJAppInfo appName])];
    }else{
        self.xieyiView = [[HomeXieYView alloc] initWithFrame:CGRectMake(0, 0,SCREEN_WIDTH, SCREEN_HEIGHT) Url:CJStringWithFormat(@"%@/agreement/agreement.html?agreementType=7",CJBaseUrl)];
        [self.xieyiView.comitButton addTarget:self action:@selector(xiYiBtnClick) forControlEvents:UIControlEventTouchUpInside];
        [ [UIApplication sharedApplication].keyWindow addSubview:self.xieyiView];
    }
    
}
- (void)xiYiBtnClick{
    [self.xieyiView removeFromSuperview];
    NSString *strURL = CJStringWithFormat(@"%@/ntocc-basic-api/authorize/imageVerify",CJBaseUrl);
    NSDictionary *dicPar = @{
        @"username":self.fieldAccount.text,
        @"branchCode":self.strBranchCode
    };
    @weakify(self);
    [[HDNetworking sharedHDNetworking] dataTaskWithHTTPMethod:GetType url:strURL parameters:dicPar status:ArpaDefault success:^(id  _Nonnull responseObject) {
        @strongify(self);
        NSDictionary *dic = (NSDictionary *)responseObject;
        //            needImage：0不需要，1需要
        NSString *needImage = CJStringWithFormat(@"%@",dic[@"needImage"]);
        if ([needImage isEqualToString:@"1"]) {
            
            [[ImgVAouthCode shared] initWithPhoneNum:self.fieldAccount.text ClickOnSure:^(NSString * _Nonnull strSure) {
                
                self.fieldAouthCode.text = strSure;
                [self allowLogInAction];
            } ClickOnCancle:^(NSString * _Nonnull strCancle) {
                
            }];
            
        }else{
            [self allowLogInAction];
        }
        
    } failure:^(NSError * _Nonnull error) {
        
    }];
}


/// 直接登录
- (void)allowLogInAction{
    [self.view endEditing:NO];

    if (![CJRegular getcheckPhone:self.fieldAccount.text]) {
        [[[AFViewShaker alloc] initWithView:self.fieldAccount] shakeWithDuration:[ShakerTime floatValue] completion:^{
            [CJAlert showStringDismissWithDelay:CJPhoneNumError];
        }];
    }
    else if ([self.strBranchCode isEqualToString:@""]){
        [CJAlert showStringDismissWithDelay:@"请选择机构"];
    }else if (self.isAgree == NO){
        [CJAlert showStringDismissWithDelay:CJStringWithFormat(@"请阅读并同意《%@隐私政策》",[CJAppInfo appName])];
    }else{
        
        if ([CJControl getIsLoginNeedSMS]) {
            if ([CJRegular getIsStrEmpty:self.fieldAouthCode.text]) {
                [[[AFViewShaker alloc] initWithView:self.fieldAouthCode] shakeWithDuration:[ShakerTime floatValue] completion:^{
                    [CJAlert showStringDismissWithDelay:@"请填写验证码"];
                }];
                return;
            }
        }
        
        NSString *strTime = [CJDateTime getCurrentTimesType:CJDateTimeModeYMDHMSAndString];
        NSString *strUrl = CJStringWithFormat(@"%@/ntocc-basic-api/authorize",CJBaseUrl);
        NSDictionary *dicPra = @{
            @"username":self.fieldAccount.text,
            @"password":[CJControl base64:CJStringWithFormat(@"%@_arpa_%@",self.fieldPW.text,strTime)],
            @"login_type":@"SHIPMENT",
            @"device_id":[CJControl getDeviceUUID],
            @"response_type":@"token",
            @"grant_type":@"password",
            @"client_secret":@"e9d0139b041b11ea97dffa163e9d2a18",
            @"client_id":@"3dd160ba0f4111e18a97dffa163e9ios",
            @"time":strTime,
            @"branchCode":self.strBranchCode,
            @"phoneCode":[CJControl getThreeUnaryValueStr:self.fieldAouthCode.text],
            @"versionCode":@"1"
        };
        
        @weakify(self);
        [[HDNetworking sharedHDNetworking] POST:strUrl parameters:dicPra success:^(id  _Nonnull responseObject) {
            
            @strongify(self);
            [CJControl getIsFirstLogInSucess];
            NSString *access_token = responseObject[@"access_token"];
            CJSaveMyDefault(CJLogInResponseToken, access_token);
            CJSaveMyDefault(CJLogInResponseBranch, responseObject[@"branch"]);
            CJSaveMyDefault(CJLogInResponseShippmentInfo, responseObject[@"party"]);
    
            NSDictionary *dicParty = responseObject[@"party"];
            CJSaveMyDefault(CJBranchCode, dicParty[@"branchCode"]);
            // 56
            NSDictionary *party = responseObject[@"party"];
            NSString *code = party[@"code"];
            [JPUSHService setAlias:code completion:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
               DLog(@"Alias number %ld",(long)seq);

            } seq:101];

            NSSet * set2 = [[NSSet alloc] initWithObjects:[CJControl getBranchCode], nil];
            [JPUSHService setTags:set2 completion:^(NSInteger iResCode, NSSet *iTags, NSInteger seq) {
               DLog(@"Tag number %ld",(long)seq);

            } seq:102];
            [CJNetWork getPartyUserCenterInfoSuccess:^(id  _Nullable responseObject) {
                
            }];
            
            if (self.isRegsiter) {
                [self popToRootVc];
                
            }else{
                [self pop];
            }
    
        } failure:^(NSError * _Nonnull error) {
            DLog(@"++++++++%@",error);
            
        }];
    }
    
}

@end
